package main

import (
	"context"
	"errors"
	"fmt"
	"net"

	webWay "gitee.com/wu-jin-feng/kinfu/grpc-webway"
	reflectPb "gitee.com/wu-jin-feng/kinfu/grpc-webway/demos/demo1/pb"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
)

type DemoServiceServer struct {
	reflectPb.UnimplementedDemoServiceServer
}

func (s *DemoServiceServer) GetScheme(ctx context.Context, req *reflectPb.GetSchemeReq) (*reflectPb.GetSchemeResp, error) {
	if req.Info == nil {
		return nil, errors.New("info 不能为空")
	}
	endData := &reflectPb.GetSchemeResp{
		Data: req.Path + ",gogogo",
		Info: &reflectPb.GetSchemeRespInfo{
			Info: fmt.Sprintf("这是一个info,%s", req.Info.Info),
			Name: fmt.Sprintf("作者是%s", req.Info.Name),
		},
	}
	return endData, nil
}

func httpServer(demoObj any) {
	// 新建webWay对象
	webObj := webWay.NewWebWay(webWay.Pro, "localhost:8010", gin.Recovery())
	// 注册路由对应的grpc方法
	webObj.RegisterServiceByName("/get_scheme", "GetScheme", demoObj)

	// 路由进行分组,对应分组增加不一样的中间件
	obj1 := webObj.NewGroup("v1", gin.Logger())
	obj1.RegisterServiceByName("/get_scheme", "GetScheme", demoObj)

	// 路由进行分组,对应分组增加不一样的中间件
	obj2 := webObj.NewGroup("v2", gin.Logger())
	v, _ := demoObj.(DemoServiceServer)
	obj2.RegisterServiceByFunc("/get_scheme", v.GetScheme, &reflectPb.GetSchemeReq{})
	// 组下再分组
	obj2_1 := obj2.NewGroup("/v2_1")
	obj2_1.RegisterServiceByFunc("/get_scheme", v.GetScheme, &reflectPb.GetSchemeReq{})

	// http服务启动
	webObj.ServerStart()
}

func main() {
	lis, err := net.Listen("tcp", "localhost:8089")
	if err != nil {
		panic(err)
	}
	s := grpc.NewServer()
	demoObj := &DemoServiceServer{}
	// 注册http服务
	httpServer(demoObj)
	// 注册grpc服务
	reflectPb.RegisterDemoServiceServer(s, demoObj)
	fmt.Println("grpc server: localhost:8089")
	if err := s.Serve(lis); err != nil {
		panic(err)
	}
}
